<?php
/**
 * 《商业发票明细》实现类
 *
 * @author 孙晓晔
 * @version $Id: Country.class.php 832 2010-01-06 09:17:14Z xuy $
 */
require_once(dirname(__FILE__) . '/ExpressUtil.class.php');

class InvoiceItem extends ExpressUtil {
	public $tbl = Constant::tbl_express_invoice_item;
	
	public $status = array(
		'-' => '请选择',
		'1' => '草稿',
		'2' => '正式',

		'9' => '其它',
	);

	public $orderby = array(
		'-' => '请选择',
		'amount' => '金额',
		'emp' => '报销人',
		'status' => '状态',

		'1' => '创建时间',
		'2' => '更新时间',
	);

	function __construct() {
		$request['update'] = '$Date: 2009/02/16 07:36:07 $';
		$request['revision'] = '$Revision: 1.1 $';

		parent::__construct($request);
	}

	function pretreat($controller) {
		parent::pretreat($controller);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function find($controller, $request) {
		$this->pretreat($controller);

		// $controller->assign('t1', strtotime('-3 month'));
		
		$controller->display($request, 'finance/expense/log/find');
		return true;
	}
	
	function _orderby_x($controller, $row, $px) {
		$orderby = $this->orderby['1'];
		$row['orderby_x'] = $row['createtime'];

		if (empty($px) || $px == '-' || $px == '1') {
			$controller->assign('orderby', $orderby);

			return $row;
		}

		if ($px == '2') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['modifytime'];
		}

		if ($px == 'mobile') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['mobile'];
		}

		$controller->assign('orderby', $orderby);

		return $row;
	}

	function _where($request) {		
		$type_s = $request['type_s'];
		$name_s = $request['name_s'];
		
		$amount1_s = $request['amount1_s'];
		$amount2_s = $request['amount2_s'];

		$my = $this->_my();

		if (empty($my)) {
			$where = " WHERE 1=1";
		} else {
			$where = " WHERE " . $my;
		}
		
		if (!empty($type_s) && $type_s <> '-') {
			$where .= " AND type = '" . $type_s . "'";
		}
				
		if (!empty($name_s)) {
			$where .= " AND name LIKE '%" . $name_s . "%'";
		}
		
		if (!empty($amount1_s)) {
			$where .= " AND amount >= '" . $amount1_s . "'";
		}

		if (!empty($amount2_s)) {
			$where .= " AND amount < '" . $amount2_s . "'";
		}
		
		$where .= $this->_where_default($request);
		$where = $this->_where_aa($where);

		return $where;
	}
	
	function _my() {
		if ($this->_is_admin()) {
			return '';
		}

		if ($this->_audit('149')) {
			return " office = '1'";
		}
		
		if ($this->_audit('150')) {
			return " office = '2'";
		}

		$emp = $_SESSION['id'];

		return " emp = '" . $emp . "'";
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function findPost($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$pager_option = array (
            'db' => $db,
            'sql' => $sql,
            'PageSize' => $this->pagesize,
            'CurrentPageID' => $request['p'],
            'numItems' => $request['n']
		);

		$pager = @new Pager($pager_option);
		$data = $pager->getPageData();

		if ($pager->number > 0) {

			$count = 0;
			$from = $pager->from;
			while ($count < $pager->number) {
				$row = $data[$count];
				$row = $this->_view(null, $row);

				$row['expense_t'] = $this->_expense($row['expense']);

				$row = $this->_orderby_x($controller, $row, $this->orderby_s);

				$data[$count] = $row;
				$count++;
			}
			$controller->assign_by_ref('result', $data);
			$controller->assign_by_ref('pager', $pager);
		}

		$controller->display($request, 'finance/expense/log/list');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function my($controller, $request) {

		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function add($controller, $request) {
		$this->pretreat($controller);

		$controller->assign('t1', strtotime('-3 day'));

		$controller->display($request, 'finance/expense/add');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function addPost($controller, $request) {
		$this->pretreat($controller);
		
		debug(print_r($request, true));
		
		$name = $request['name'];
		$content = addslashes($request['content']);
		$total = $request['total'];
		
		$db = newdb($this->dsn_w);

		$fmt = "INSERT INTO %s(name, content, total, emp, createtime, modifytime) VALUES('%s', '%s', '%s', '%s', now(), now())";
		$sql = sprintf($fmt, $this->tbl, $name, $content, $total, $_SESSION['id']);
		// debug($sql);
		$db->query($sql);
		
		$id = $db->insert_id();
		
		$fmt = "INSERT INTO %s(expense, `name`, amount, createtime, modifytime) VALUES('%s', '%s', '%s', now(), now())";
		while (list($k, $v) = each($request['log'])) {
			$sql = sprintf($fmt, $this->tbl, $id, $v['name'], $v['amount']);
			debug($sql);
			$db->query($sql);
		}		

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function edit($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'finance/expense/log/edit');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function editPost($controller, $request) {
		$this->pretreat($controller);
		
		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$expense = $request['expense'];
		$date = $request['date'];
		$type = $request['type'];
		
		$name = addslashes($request['name']);
		$amount = $request['amount'];

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET expense = '%s', date = '%s', type = '%s', name = '%s', amount = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $expense, $date, $type, $name, $amount, $id);
		// debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function batch_type($controller, $request) {
		$this->pretreat($controller);
		
		$insql = "in ('000000000";
		while (list($k, $v) = each($request)) {
			if (substr($k, 0, 2) == "c_") {
				$insql .= "', '" . $v;
			}
		}
		$insql .= "')";
		
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE id %s";
		$sql = sprintf($fmt, $this->tbl, $insql);
		debug($sql);
		
		$result = $db->query($sql);
		$data = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
			
			$data[] = $row;
		}
		$controller->assign_by_ref('result', $data);

		$controller->display($request, 'finance/expense/log/batch_type');
		return true;
	}
	
	function batch_typePost($controller, $request) {
		$this->pretreat($controller);
		
		$content = addslashes($request['content']);
		$type = $request['type'];

		$db = newdb($this->dsn_w);
		while (list($k, $id) = each($request['cc'])) {
			$fmt = "UPDATE %s SET type = '%s', modifytime = now() WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $type, $id);
			debug($sql);
			$db->query($sql);
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function view($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);		
		
		$row['expense_t'] = $this->_expense($row['expense']);
		
		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'finance/expense/log/view');
		return true;
	}
	
	function _view($id = 0, $row = null) {
		if ($row == null) {
			clean($this->tbl . "_id_" . $id);
			$row = $this->id($this->tbl, $id);
		}
		
		$row['mold_t'] = Name::mold($row['mold']);
		$row['mold_x'] = $row['mold'] . ":" . $row['mold_t'];
		
		$row = $this->_view_t($row);

		return $row;
	}
	
	function _expense($id) {
		if (empty($id)) {
			return '';
		}

		return Common::name_id(Constant::tbl_cw_expense, $id);
	}

	function _list($id, $status = 'all') {
		$db = newdb($this->dsn_r);
		if ($status == 'all') {
			$fmt = "SELECT * FROM %s WHERE invoice = '%s' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $id);
		} else {
			$fmt = "SELECT * FROM %s WHERE invoice = '%s' AND status = '%s' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $id, $status);
		}
		
		debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
			
			$row['ok'] = true; 

			$ret[] = $row;
		}

		return $ret;
	}
	
	function _insert($request) {
		
		$id = $request['id'];
		
		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);
		
		$customer = $this->_input($request['customer']);
		$data = json_decode($request['item'], true);
		
		$db = newdb($this->dsn_w);
		$fmt = "INSERT INTO %s(office, `invoice`, mold, name, `package`, amount, price, w1, w2, len, ww, hh, content, emp, oper, ";
		$fmt .= "createtime, modifytime) VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
		while (list($k, $v) = each($data)) {
			if (!$this->_ok($v['ok'])) {
				continue;
			}
			
			$mold = $this->_input($v['mold_x']);
			
			$name = addslashes(trim($v['name']));			
			if (empty($name)) {
				continue;
			}
			
			$content = addslashes(trim($v['content']));
			
			$sql = sprintf($fmt, $this->tbl, $office, $id, $mold, $name, $v['package'], $v['amount'], $v['price'], $v['w1'], $v['w2'], $v['len'], $v['ww'], $v['hh'], $content, $emp, $_SESSION['id']);
			debug($sql);
			$db->query($sql);
		}
		
		$fmt = "UPDATE %s SET customer = '%s' WHERE `invoice` = '%s'";
		$sql = sprintf($fmt, $this->tbl, $customer, $id);
		debug($sql);
		$db->query($sql);
	}

	function _update($request) {
		$id = $request['id'];
		
		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);
		
		$customer = $this->_input($request['customer']);
		$data = json_decode($request['item'], true);
		
		$db = newdb($this->dsn_w);		
		while (list($k, $v) = each($data)) {
			$name = addslashes(trim($v['name']));			
			if (empty($name)) {
				continue;
			}
			
			$mold = $this->_input($v['mold_x']);
			$content = addslashes(trim($v['content']));
						
			if (array_key_exists("createtime", $v)) {
				if ($v['status'] > 1) {
					continue;
				}
				
				if (!$this->_ok($v['ok'])) {
					$fmt = "DELETE FROM %s WHERE id = '%s'";
					$sql = sprintf($fmt, $this->tbl, $v['id']);
				} else {
					$fmt = "UPDATE %s SET customer = '%s', mold = '%s', name = '%s', `package` = '%s', amount = '%s', price = '%s', w1 = '%s', w2 = '%s', `len` = '%s', ww = '%s', hh = '%s', content = '%s', modifytime = now() WHERE id = '%s'";
					$sql = sprintf($fmt, $this->tbl, $customer, $mold, $name, $v['package'], $v['amount'], $v['price'], $v['w1'], $v['w2'], $v['len'], $v['ww'], $v['hh'], $content, $v['id']);
				}			
			} else {
				if (!$this->_ok($v['ok'])) {
					continue;
				}
			
				$fmt = "INSERT INTO %s(office, `invoice`, mold, name, `package`, amount, price, w1, w2, `len`, ww, hh, content, emp, oper, ";
				$fmt .= "createtime, modifytime) VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
				$sql = sprintf($fmt, $this->tbl, $office, $id, $mold, $name, $v['package'], $v['amount'], $v['price'], $v['w1'], $v['w2'], $v['len'], $v['ww'], $v['hh'], $content, $emp, $_SESSION['id']);			
			}
			
			debug($sql);
			$db->query($sql);
		}
				
		$fmt = "UPDATE %s SET customer = '%s' WHERE `invoice` = '%s'";
		$sql = sprintf($fmt, $this->tbl, $customer, $id);
		debug($sql);
		$db->query($sql);
	}

	function _delete($id) {
		$db = newdb($this->dsn_w);
		$fmt = "DELETE FROM %s WHERE expense = '%s'";
		$sql = sprintf($fmt, $this->tbl, $id);
		debug($sql);
		$db->query($sql);
	}
		
	function delete($controller, $request) {
		$this->pretreat($controller);

		$db = newdb($this->dsn_w);
		while (list($k, $id) = each($request)) {
			if (substr($k, 0, 2) <> "c_") {
				continue;
			}
			
			$row = $this->_view($id);
			if (!$this->_is_delete($row)) {
				continue;
			}

			$this->_delete3($id);
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function _delete3($id) {
		$db = newdb($this->dsn_w);
		if ($this->_is_admin()) {
			$fmt = "DELETE FROM %s WHERE id = '%s'";
		} else {
			$fmt = "UPDATE %s SET visible = 2 WHERE id = '%s'";
		}
		
		$sql = sprintf($fmt, $this->tbl, $id);
		debug($sql);
		$db->query($sql);
	}
	
	function _is_delete($row) {
		if ($this->_is_admin()) {
			return true;
		}

		if ($row['status'] > 2) {
			return false;
		}

		if ($this->_audit('77')) {
			return true;
		}

		if ($row['oper'] == $_SESSION['id']) {
			return true;
		}

		return false;
	}
	
	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function ajax_code($controller, $request) {

		$data = $this->_ajax_code($request);
		echo json_encode($data);
	}

	function _ajax_code($request) {
		$q = $request['q'];
		$n = $request['maxRows'];
		if (empty($n)) {
			$n = 20;
		}
		
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE status = '1' AND code LIKE '%s' ORDER BY id DESC";
		$sql = sprintf($fmt, $this->tbl, $q . "%");
		// debug($sql);
		$result = $db->query($sql);

		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row['emp_t'] = Name::emp($row['emp']);

			$ret[] = $row;
		}

		return $ret;
	}
}
?>